import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from "@/views/Login.vue";
import Admin from "@/views/Admin.vue";
import Welcome from "@/views/admin/Welcome.vue";
import Chapter from "@/views/admin/Chapter.vue";
import Section from "@/views/admin/Section.vue";
import Course from "@/views/admin/Course.vue";
import Category from "@/views/admin/Category.vue";
import Teacher from "@/views/admin/Teacher.vue";
import Member from "@/views/admin/Member.vue";
import Sms from "@/views/admin/Sms.vue";
import File from "@/views/admin/File.vue";
import CourseContent from "@/views/admin/CourseContent.vue";
import User from "@/views/admin/User.vue";
import Resource from "@/views/admin/Resource.vue";
import Role from "@/views/admin/Role.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    name: 'admin',
    component: Admin,
    meta: {
      loginRequire: true
    },
    children: [
      {
        path: 'welcome',
        name: 'welcome',
        component: Welcome,
      },
      {
        path: 'business/chapter',
        name: 'business/chapter',
        component: Chapter,
      },
      {
        path: 'business/section',
        name: 'business/section',
        component: Section,
      },
      {
        path: 'business/course',
        name: 'business/course',
        component: Course,
      },
      {
        path: 'business/content',
        name: 'business/content',
        component: CourseContent,
      },
      {
        path: 'business/category',
        name: 'business/category',
        component: Category,
      },
      {
        path: 'business/teacher',
        name: 'business/teacher',
        component: Teacher,
      },
      {
        path: 'business/member',
        name: 'business/member',
        component: Member,
      },
      {
        path: 'business/sms',
        name: 'business/sms',
        component: Sms,
      },
      {
        path: 'file/file',
        name: 'file/file',
        component: File,
      },
      {
        path: 'system/user',
        name: 'system/user',
        component: User,
      },
      {
        path: 'system/resource',
        name: 'system/resource',
        component: Resource,
      },
      {
        path: 'system/role',
        name: 'system/role',
        component: Role,
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由登录拦截
router.beforeEach((to, from, next) => {
  // 要不要对 loginRequire 做登录拦截
  if (to.matched.some((item) => {
    return item.meta.loginRequire
  })) {
    let loginUser = JSON.parse(<string>sessionStorage.getItem("SESSION_KEY_LOGIN_USER"));
    if (loginUser === null) {
      console.log("未登录")
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router
